package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
//service就不用写crud的方法了，支持单表的

@Service
public class IWmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {


    //频道分页列表根据名称模糊查询
    @Override
    public PageResponseResult listByName(ChannelDto channelDto) {

        //模拟异常
//        int i = 1 /0;

        //构建查询条件
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();

        //进行模糊查询，先判断前面传来的值是否为空
        if (StringUtils.isNotEmpty(channelDto.getName())) {
            queryWrapper.like(WmChannel::getName, channelDto.getName());
        }

        //2.构建分页对象Page - 封装分页 页码，页大小
        IPage<WmChannel> ipage = new Page<>(channelDto.getPage(), channelDto.getSize());

        //3.进行查询
        ipage = this.page(ipage, queryWrapper);

        //4.返回结果
        PageResponseResult<List<WmChannel>> responseResult = new PageResponseResult<>(channelDto.getPage(), channelDto.getSize(), ipage.getTotal(), ipage.getRecords());
        return responseResult;
    }


    //保存频道
    @Override
    public ResponseResult saveChannel(WmChannel wmChannel) {

        //先判断是否为空
        if (wmChannel == null || StringUtils.isEmpty(wmChannel.getName())) {
            //返回错误的信息
            return PageResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询当前的频道是否已经存在
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName, wmChannel.getName());
        WmChannel one = this.getOne(queryWrapper);

        if (one != null) {
            //已经存在，返回已经存在的信息
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }

        //不存在，则是新增
        this.save(wmChannel);

        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }
}
